package org.freeone.k8s.web.knife.utils;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.concurrent.TimeUnit;

/**
 * IP城市定位

 */
@Component
public class IPUtils {
//    private static final String DB_PATH = "C:\\Users\\yanyunfan\\Downloads\\ip2region.db";
    private static final String DEFAULT_CITY_NAME = "未知";


    @Value("classpath:ip2region.xdb")
//    @Value("classpath:logback-spring.xml")
    private Resource ip2region_xdb;

    // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
    private Searcher searcher;

    @PostConstruct
    public void init() throws IOException {
        String dbPath = ip2region_xdb.getFile().getAbsolutePath();

        // 1、从 dbPath 加载整个 xdb 到内存。
        byte[] cBuff ;
        try {
            cBuff = Searcher.loadContentFromFile(ip2region_xdb.getFile().getAbsolutePath());
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {


        }


    }

    public void search(String ip) throws Exception {

        long sTime = System.nanoTime();
        String region = searcher.search(ip);
        long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
        System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
    }

}
